using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using WeifenLuo.WinFormsUI.Base;
using WeifenLuo.WinFormsUI.Security;

namespace HRM
{
    public partial class FormGroupInfo : FormBaseData
    {
        private DataSet mdsGroups;
        private DataSet mdsUsersGroups;
        private DataRow mdrUsersGroup;
        private DataSet mdsUsers;
        private DataRow mdrUsers;
        private DataView mUsersGroupsView;
        private CurrencyManager mRowManagerDetail;
        private Ctrl_Security mCtrlScur;

        public FormGroupInfo()
        {
            InitializeComponent();
        }

        private void btnRemove_Click(object sender, System.EventArgs e)
        {
            if (!btnRemove.Enabled || lstUsersBelongGroup.SelectedItem == null) return;
            try
            {
                if (mdsUsersGroups.Tables[0].Rows.Count == 0)
                {
                    btnRemove.Enabled = false;
                    return;
                }
                mRowManagerDetail.EndCurrentEdit();
                DataRow ldrUsersGroups = mdrUsersGroup;
                ldrUsersGroups.Delete();
                lstUsersBelongGroup.Items.RemoveAt(lstUsersBelongGroup.SelectedIndex);
                btnAdd.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAdd_Click(object sender, System.EventArgs e)
        {
            // Adding the group that this user is belong to.
            if (!btnAdd.Enabled || lstAvailableUsers.SelectedItem == null) return;
            try
            {
                mdrUsers = mdsUsers.Tables[0].Rows[lstAvailableUsers.SelectedIndex];
                DataRow ldrUsersGroups;

                for (int li_index = 0; li_index < mUsersGroupsView.Count; li_index++)
                {
                    DataRowView opv = mUsersGroupsView[li_index];
                    ldrUsersGroups = opv.Row;
                    if (mdrUsers["ID_User"].ToString() == ldrUsersGroups["ID_User"].ToString()) return;
                }
                mRowManagerDetail.EndCurrentEdit();
                mRowManagerDetail.AddNew();
                mRowManagerDetail.Position = mRowManagerDetail.Count - 1;
                ldrUsersGroups = mdsUsersGroups.Tables[0].Rows[mRowManagerDetail.Position];
                ldrUsersGroups["ID_Group"] = txtGroupID.Text.Trim();
                ldrUsersGroups["ID_User"] = mdrUsers["ID_User"];
                ldrUsersGroups["UpdateTime"] = DateTime.Now;
                lstUsersBelongGroup.Items.Add(mdrUsers["ID_User"]);
                btnRemove.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        protected override void LoadMasterData()
        {
            lblStatus = lblstatus;
            btnOk = btnok;
            btnCancel = btncancel;
            // Load into the Textboxes, and the List boxes
            mCtrlScur = new Ctrl_Security();
            mdsGroups = new DataSet();

            mdsGroups = mCtrlScur.GetGroups();

            txtGroupID.DataBindings.Add(new Binding("Text", mdsGroups.Tables[0], "ID_Group"));
            txtDescription.DataBindings.Add(new Binding("Text", mdsGroups.Tables[0], "Description"));

            mRowManager = (CurrencyManager)txtGroupID.BindingContext[mdsGroups.Tables[0]];
            SetData2List(mdsGroups);
            // Loading the user group
            LoadUserInGroup();

            // Loading the available group
            mdsUsers = mCtrlScur.GetAllUsers();
            lstAvailableUsers.DataSource = mdsUsers.Tables[0];
            lstAvailableUsers.DisplayMember = "ID_User";

            SetReadOnly(true);
            base.LoadMasterData();
        }

        protected override void BaseForm_Activated(object sender, System.EventArgs e)
        {
            base.BaseForm_Activated(sender, e);
        }

        protected override void BasicForm_Closing(object sender, FormClosingEventArgs e)
        {
            base.BasicForm_Closing(sender, e);
        }

        protected override void BaseForm_KeyDown(object sender, KeyEventArgs e)
        {
            base.BaseForm_KeyDown(sender, e);
        }

        private void LoadUserInGroup()
        {	// Load user group depending on the user.
            mdsUsersGroups = new DataSet();
            mdsUsersGroups = mCtrlScur.GetUsersInGroup(txtGroupID.Text);
            mUsersGroupsView = mdsUsersGroups.Tables[0].DefaultView;

            mUsersGroupsView.Sort = "ID_User";
            lstUsersBelongGroup.DisplayMember = mUsersGroupsView.Sort;
            lstUsersBelongGroup.Items.Clear();
            foreach (DataRowView lOV in mUsersGroupsView)
                lstUsersBelongGroup.Items.Add(lOV);

            mRowManagerDetail = (CurrencyManager)lstUsersBelongGroup.BindingContext[mUsersGroupsView];
            mRowManagerDetail.PositionChanged += new EventHandler(RowList_Changed);
            mRowManagerDetail.ItemChanged += new ItemChangedEventHandler(ItemList_Changed);
            if (mUsersGroupsView.Count > 0)
                mdrUsersGroup = mdsUsersGroups.Tables[0].Rows[0];
        }

        private void SetReadOnly(bool ab_switch)
        {
            txtGroupID.ReadOnly = ab_switch;
            txtDescription.ReadOnly = ab_switch;
        }

        private void RowList_Changed(object sender, System.EventArgs e)
        {	// if the currencymanager detects a positional event set the 'current' object for reference in delete method
            CurrencyManager CM = (CurrencyManager)sender;
            if (CM.Position != -1)
            {
                DataRowView Current = (DataRowView)CM.Current;
                mdrUsersGroup = Current.Row;
            }
        }

        private void ItemList_Changed(object sender, ItemChangedEventArgs e)
        {	// if the currencymanager detects a value change event show the new details in the form controls
            CurrencyManager CM = (CurrencyManager)sender;
            if (CM.Position != -1)
            {
                DataRowView Current = (DataRowView)CM.Current;
                mdrUsersGroup = Current.Row;
            }
        }

        public override void RowMaster_Changed(object sender, EventArgs e)
        {
            base.RowMaster_Changed(sender, e);
            LoadUserInGroup();
        }

        public override void add()
        {
            base.add();
            SetReadOnly(false);
            // cannot Add/Remove User in the ADD mode.
            btnAdd.Enabled = false;
            btnRemove.Enabled = false;
            mRowManager.EndCurrentEdit();
            mRowManager.AddNew();
        }

        public override void delete()
        {
            // Check the group(A) whether contains any user or not.
            //		If the group wouldn't containt any user
            //			--> show the confirm message (call base.delete())
            //			If the actor say yes --> delete it.
            //		Else (the group containts at least one user)
            //			Show message to info the actor 
            // Besides, before deleting this group, the ObjectsGroups that concerns to this Group must be deleted.
            // This action will be occured in the controller by calling the store procedures.
            if (txtGroupID.Text == "ADMIN")
            {// Group Admin cannot be deleted
                MessageBox.Show("Group Admin cannot be deleted", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (lstUsersBelongGroup.Items.Count > 0)
            {
                // Cannot delte this group. We must delete all the user that belong with this group.
                MessageBox.Show("We must delete all the user that belong with this group.", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            base.delete();
            if (!mb_AcceptDelete) return; // confirm delete

            DataRow ldrGroup = mdsGroups.Tables[0].Rows[mRowManager.Position];

            // Delete ObjectsGroups b4 updating into the Database
            if (!mCtrlScur.DeleteObjectsGroup(ldrGroup["ID_Group"].ToString()))
            {
                MessageBox.Show("Delete Groups b4 updating into the Database, Error from store procedure.", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                mRowManager.Position = mdsGroups.Tables[0].Rows.Count - 1;
                return;
            }
            ldrGroup.Delete();
            string ls_NotNullCol, ls_tableName;
            string ls_errorMsg = mCtrlScur.UpdateGroups(mdsGroups, out ls_NotNullCol, out ls_tableName);
            if (ls_errorMsg != "")
            {
                if (ls_NotNullCol != "" || ls_tableName != "")
                {
                    string[] lsa_param = { ls_NotNullCol, ls_tableName };
                    MessageBox.Show(lsa_param[0] + " cannot be empty", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                    MessageBox.Show("DB Error", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                mRowManager.Position = mdsGroups.Tables[0].Rows.Count - 1;
            }
            base.post_delete();
        }

        public override void modify()
        {
            btnAdd.Enabled = true;
            btnRemove.Enabled = true;
            SetReadOnly(false);
            base.modify();
        }

        public override void save()
        {
            // Add your code here
            mRowManager.EndCurrentEdit();
            string ls_NotNullCol, ls_tableName;
            string ls_errorMsg = mCtrlScur.UpdateGroups(mdsGroups, out ls_NotNullCol, out ls_tableName);
            if (ls_errorMsg != "")
            {
                if (ls_NotNullCol != "" || ls_tableName != "")
                {
                    string[] lsa_param = { ls_NotNullCol, ls_tableName };
                    MessageBox.Show(lsa_param[0] + " cannot be empty", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                    MessageBox.Show("DB Error", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (GetCurrentAction() == MODES.ADD)
            {
                DataRow ldrUsersGroups;
                DataRow ldrGroups = mdsGroups.Tables[0].Rows[mRowManager.Position];
                for (int i = 0; i < lstUsersBelongGroup.Items.Count; i++)
                {
                    ldrUsersGroups = mdsGroups.Tables[0].Rows[i];
                    ldrUsersGroups["ID_Group"] = txtGroupID.Text.Trim();
                    ldrUsersGroups["UpdateTime"] = DateTime.Now;
                }
            }

            ls_errorMsg = mCtrlScur.UpdateUsersGroup(mdsUsersGroups, out ls_NotNullCol, out ls_tableName);
            if (ls_errorMsg != "")
            {
                if (ls_NotNullCol != "" || ls_tableName != "")
                {
                    string[] lsa_param = { ls_NotNullCol, ls_tableName };
                    MessageBox.Show(lsa_param[0] + " cannot be empty", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                    MessageBox.Show("DB Error", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            // Copy all of the functionalities to the new Group, 
            //	this had already done in the Trigger of the Groups table.

            btnAdd.Enabled = false;
            btnRemove.Enabled = false;
            SetReadOnly(true);
            base.save();
        }

        public override void cancel()
        {
            btnAdd.Enabled = false;
            btnRemove.Enabled = false;
            mRowManager.EndCurrentEdit();
            mRowManagerDetail.EndCurrentEdit();
            mdsGroups.RejectChanges();
            mdsUsersGroups.RejectChanges();
            LoadUserInGroup();
            base.cancel();
        }

        private void lstUsersBelongGroup_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            mRowManagerDetail.Position = lstUsersBelongGroup.SelectedIndex;
        }

        private void btnok_Click(object sender, System.EventArgs e)
        {
            save();
        }

        private void btncancel_Click(object sender, System.EventArgs e)
        {
            cancel();
        }

        protected override void BasicForm_Load(object sender, EventArgs e)
        {
            base.BasicForm_Load(sender, e);
            mMainForm.Refresh();
            this.WindowState = FormWindowState.Normal;
        }
    }
}